import type { QuickSearchTag } from '../../../components/search/types'
import type { SortOption } from '../../../components/sort_order/types'
import type { BadgeStyleConfig, OrderType } from '../../../types/interfaces'
import { generateBadgeStyles } from '../../../components/navigator_bar/types'
import { SearchBox } from '../../../components/search'
import { SortOrder } from '../../../components/sort_order'
import { BaseModule } from '../../../lib/abstract'
import { ThemeVarService } from '../../../lib/abstract/style/theme_var/service'
import { ICON_IDS } from '../../../lib/icons/types/constants'
import { ToolKit } from '../../../lib/utils/toolkit'
import {
  AppStyleCollections,
  BodyClasses,
  logger,
  PROJECT_PREFIX,
} from '../../../types/constants'
import { PAGE_CONTENT_WIDTH } from '../../../types/constants/offical'
import { ConfigManager } from '../../config_manager'

/**
 * 回答导航项基础信息
 */
export interface IAnswerNavigationItem {
  /** 回答序号 (从1开始) */
  index: number

  /** 用户名（可选） */
  username?: string

  /** 用户头像（可选） */
  avatar?: string

  /** 楼层显示文本（如"#1楼"） */
  floorCount?: string

  /** 赞同文本（可选） */
  voteText?: string

  /**
   * 赞同数量（可选）
   */
  voteCount?: number

  /** 评论文本（可选） */
  commentText?: string
  /**
   * 评论数量（可选）
   */
  commentCount?: number

  /** 喜欢文本（可选） */
  likeText?: string

  /** 更新时间（可选） */
  updateTime?: string

  /** 回答摘要 */
  excerpt?: string

  /** 是否高亮 */
  highlight?: boolean
}

interface Config {
  enabled?: boolean
  container?: string
  position?: 'top' | 'bottom'
  showSearch?: boolean
  showSortButton?: boolean
  maxHeight?: string
  defaultSortOrder?: OrderType
}

const searchMap: QuickSearchTag[] = [
  {
    type: 'hot',
    label: '热门',
    bgColor: 'rgba(255, 152, 0, 0.1)',
    textColor: '#ff9800',
    hoverBgColor: 'rgba(255, 152, 0, 0.2)',
  },
  {
    type: 'liked',
    label: '喜欢',
    bgColor: 'rgba(244, 67, 54, 0.1)',
    textColor: '#d32f2f',
    hoverBgColor: 'rgba(244, 67, 54, 0.2)',
  },
  {
    type: 'upvoted',
    label: '已赞同',
    bgColor: 'rgba(76, 175, 80, 0.1)',
    textColor: '#4caf50',
    hoverBgColor: 'rgba(76, 175, 80, 0.2)',
  },
  {
    type: 'top-vote',
    label: '热评',
    bgColor: 'rgba(255, 193, 7, 0.1)',
    textColor: '#ffc107',
    hoverBgColor: 'rgba(255, 193, 7, 0.2)',
  },
  {
    type: 'top-comment',
    label: '热议',
    bgColor: 'rgba(33, 150, 243, 0.1)',
    textColor: '#2196f3',
    hoverBgColor: 'rgba(33, 150, 243, 0.2)',
  },
]

const sortOptions: SortOption[] = [
  { value: 'floor', label: '按楼层' },
  { value: 'vote', label: '按赞同数' },
  { value: 'comment', label: '按评论数' },
  { value: 'time', label: '按更新时间' },
]

const badgeStyleConfigs: BadgeStyleConfig[] = [
  {
    type: 'top-vote',
    backgroundColor: '#fff8e1',
    textColor: '#ff8f00',
    borderColor: '#ffd54f',
    defaultDisplay: 'inline-block',
  },
  {
    type: 'top-comment',
    backgroundColor: '#e3f2fd',
    textColor: '#1565c0',
    borderColor: '#90caf9',
    defaultDisplay: 'inline-block',
  },
  {
    type: 'upvoted',
    backgroundColor: `var(${ThemeVarService.getInstance().upvote.background})`,
    textColor: `var(${ThemeVarService.getInstance().upvote.text})`,
    borderColor: `var(${ThemeVarService.getInstance().upvote.borderColor})`,
    defaultDisplay: 'none',
    activeDisplay: 'inline-block',
  },
  {
    type: 'liked',
    backgroundColor: `var(${ThemeVarService.getInstance().liked.background})`,
    textColor: `var(${ThemeVarService.getInstance().liked.text})`,
    borderColor: `var(${ThemeVarService.getInstance().liked.borderColor})`,
    defaultDisplay: 'none',
    activeDisplay: 'inline-block',
  },
]

export class AnswerNavigator extends BaseModule {
  id: string = 'answer-navigator'
  name: string = 'AnswerNavigator'
  isInitialized: boolean = false
  readonly supportedPlatforms: string[] = ConfigManager.getInstance().moduleSupportedPlatforms(this.name)
  private readonly emptyAvatarUrl: string = 'https://picx.zhimg.com/v2-abed1a8c04700ba7d72b45195223e0ff_l.jpg?source=1def8aca'
  private readonly className: string = AppStyleCollections.Module.ANSWER_NAVIGATOR.class
  private readonly selector: string = `.${this.className}`
  public static readonly DOM_HEIGHT: string = '70px'
  private static instance: AnswerNavigator
  private searchBox: SearchBox
  private sortOrderComponent: SortOrder
  $element: JQuery | undefined
  private itemsCount: number = 0
  private currentIndex: number = 1
  private isDropdownOpen: boolean = false
  private currentItems: IAnswerNavigationItem[] = []
  private searchQuery: string = ''
  private isQuickTagSearch: boolean = false
  private sortOrder: OrderType = 'asc'
  private sortType: string = 'floor'

  defaultConfig: Config = {
    enabled: true,
    container: 'body',
    position: 'top',
    showSearch: true,
    showSortButton: true,
    maxHeight: '60vh',
    defaultSortOrder: 'asc',
  }

  constructor(config?: Config | object) {
    super()

    this.config = {
      ...this.defaultConfig,
      ...config,
    }

    this.searchBox = new SearchBox({
      id: 'answer-search',
      placeholder: '搜索回答，试试输入「热门」查看内容...',
      showQuickSearch: true,
      quickSearchTags: searchMap,
      onSearch: (value, QuickSearch: boolean) => {
        this.searchQuery = value.toLowerCase().trim()
        this.renderList()
        if (QuickSearch) {
          this.isQuickTagSearch = false
        }
      },
      onQuickTagClick: (type) => {
        this.isQuickTagSearch = true
        this.handleQuickSearch(type)
      },
    })

    // 初始化排序组件
    this.sortOrderComponent = new SortOrder({
      order: this.sortOrder,
      type: this.sortType,
      options: sortOptions,
      onChange: (type, order) => {
        this.sortType = type
        this.sortOrder = order
        this.renderList()
      },
    })
  }

  /**
   * 获取单例实例
   */
  public static getInstance(config?: Config | object): AnswerNavigator {
    if (!AnswerNavigator.instance) {
      AnswerNavigator.instance = new AnswerNavigator(config)
    }

    return AnswerNavigator.instance
  }

  destroy(): void {
    this.$element?.off().remove()
    $(document).off('click.answerNavigator')

    super.destroy()
  }

  core(): void {
    this.loadConfig()

    if (!this.config.enabled)
      return

    this.mount()
  }

  onToggleCallback(_id: string, checked: boolean): void {
    super.onToggleCallback(_id, checked)
  }

  mount(): void {
    this.$element = this.createNavigator()
    this.initEventListeners()
  }

  /**
   * 创建导航器 DOM 结构
   */
  private createNavigator(): JQuery {
    const positionClass = this.config.position === 'bottom' ? 'position-bottom' : ''
    const searchBox = this.config.showSearch
      ? this.searchBox.render()
      : ''
    const sortBox = this.config.showSortButton
      ? this.sortOrderComponent.render()
      : ''

    return $(`
      <div class="${this.className} ${BodyClasses.IS_EMPTY} ${positionClass}">
        <div class="current-item">
          <img class="avatar" src="" alt="">
          <div class="meta">
            <div class="header">
              <span class="username"></span>
              <span class="floor"></span>
              <span class="badge upvoted"></span>
              <span class="badge liked"></span>
            </div>
            <div class="stats">
              <span class="stat votes">
                <span class="icon">👍</span>
                <span class="count">0</span>
              </span>
              <span class="stat comments">
                <span class="icon">💬</span>
                <span class="count">0</span>
              </span>
              <span class="stat time">
                <span class="icon">🕒</span>
                <span class="count">未知</span>
              </span>
            </div>
          </div>
          <div class="navigator-info">
            <span class="current-index">0</span>
            <span class="total-count">/0</span>
          </div>
          <div class="toggle"></div>
        </div>
        <div class="dropdown">
          ${searchBox}
          <div class="sort-box">
            ${sortBox}
          </div>
          <div class="list"></div>
        </div>
      </div>
    `).appendTo(this.config.container || 'body')
  }

  /**
   * 初始化事件监听
   */
  private initEventListeners(): void {
    // 切换下拉菜单
    this.$element?.find('.current-item').on('click', () => this.toggleDropdown())

    // 点击外部关闭
    $(document).on('click.answerNavigator', (e) => {
      if (!this.$element?.get(0)?.contains(e.target)) {
        this.closeDropdown()
      }
    })

    if (!this.$element)
      return

    // 挂载搜索
    this.searchBox?.mount(this.$element)
    // 挂载排序
    this.sortOrderComponent?.mount(this.$element)
  }

  private handleQuickSearch(type: string): void {
    const label = searchMap.filter(item => item.type === type)[0]?.label

    if (!type || !label)
      return

    this.searchBox.enableQuickSearch()
    this.searchBox.setValue(label)
  }

  private toggleDropdown(): void {
    this.isDropdownOpen = !this.isDropdownOpen
    this.$element?.toggleClass('expanded', this.isDropdownOpen)
    if (!this.$element?.hasClass('expanded')) {
      this.clearSearch()
    }
  }

  private clearSearch(): void {
    this.searchBox.setValue('')
  }

  private closeDropdown(): void {
    this.isDropdownOpen = false
    this.$element?.removeClass('expanded')
    this.clearSearch()
  }

  updateOptions(items: IAnswerNavigationItem[]): void {
    this.itemsCount = items.length
    this.currentItems = items
    let currentIndex = this.currentIndex
    const currentItem = items[currentIndex]

    if (!currentItem) {
      this.setCurrentIndex(1)
      currentIndex = 1
    }

    this.renderList(items)
    this.renderCurrentItem(Math.max(currentIndex, 1))

    const $container = this.$element?.closest(this.selector)
    const isEmpty = $container?.hasClass(BodyClasses.IS_EMPTY) || true
    if (items.length > 1 && $container && isEmpty) {
      $container.removeClass(BodyClasses.IS_EMPTY)
    }
    else if (items.length === 0 && $container && !isEmpty) {
      $container.addClass(BodyClasses.IS_EMPTY)
    }

    this.updateCounter()
  }

  /**
   * 渲染当前项
   * @param floor 项索引
   */
  private renderCurrentItem(floor: number): void {
    if (!this.$element)
      return

    const $item = this.$element.find(`.current-item`)

    const $currentIndexItem = this.$element.find(`.list .item[data-floor="${floor}"]`)

    if (!$currentIndexItem || !$currentIndexItem.length) {
      this.$element.addClass(BodyClasses.IS_EMPTY)
      return
    }

    // 基础信息配置
    const baseFields = [
      { selector: '.avatar', attr: 'src', fallback: this.emptyAvatarUrl },
      { selector: '.username', prop: 'text', fallback: '未知' },
      { selector: '.floor', prop: 'text', fallback: '0' },
      { selector: '.votes .count', prop: 'text', fallback: '0' },
      { selector: '.comments .count', prop: 'text', fallback: '0' },
      { selector: '.time .count', prop: 'text', fallback: '未知' },
    ]

    // 徽章配置
    const badgeConfig = [
      {
        selector: '.badge.upvoted',
        condition: $currentIndexItem.find('.badge.upvoted').length > 0,
        activeText: '已赞同',
        inactiveText: '',
      },
      {
        selector: '.badge.liked',
        condition: $currentIndexItem.find('.badge.liked').length > 0,
        activeText: '喜欢',
        inactiveText: '',
      },
    ]

    // 处理基础信息
    baseFields.forEach((field) => {
      const $target = $item.find(field.selector)
      const value = field.attr
        ? $currentIndexItem.find(field.selector).attr(field.attr) || field.fallback
        : $currentIndexItem.find(field.selector).text() || field.fallback

      if (field.attr) {
        $target.attr(field.attr, value)
      }
      else {
        $target.text(value)
      }
    })

    // 处理徽章状态
    badgeConfig.forEach((badge) => {
      const $badge = $item.find(badge.selector)
      $badge.text(badge.condition ? badge.activeText : badge.inactiveText)
      $badge.toggleClass('active', badge.condition)
    })
  }

  /**
   * 排序回答项
   * @param items 回答项数组
   * @returns 排序后的回答项数组
   */
  private sortItems(items: IAnswerNavigationItem[]): IAnswerNavigationItem[] {
    return [...items].sort((a, b) => {
      switch (this.sortType) {
        case 'vote':
        // 按赞同数排序
        {
          const aVotes = a.voteCount || 0
          const bVotes = b.voteCount || 0
          return this.sortOrder === 'asc' ? aVotes - bVotes : bVotes - aVotes
        }

        case 'comment':
        // 按评论数排序
        { const aComments = a.commentCount || 0
          const bComments = b.commentCount || 0
          return this.sortOrder === 'asc' ? aComments - bComments : bComments - aComments }

        case 'time':
        // 按更新时间排序
        { const aTime = new Date(a.updateTime || 0).getTime()
          const bTime = new Date(b.updateTime || 0).getTime()
          return this.sortOrder === 'asc' ? aTime - bTime : bTime - aTime }

        case 'floor':
        default:
        // 默认按楼层排序
        { const aFloor = Number.parseInt(a.floorCount || '0')
          const bFloor = Number.parseInt(b.floorCount || '0')
          return this.sortOrder === 'asc' ? aFloor - bFloor : bFloor - aFloor }
      }
    })
  }

  private renderList(items?: IAnswerNavigationItem[]): void {
    if (!this.$element)
      return

    const dataSource = items || this.currentItems

    if (!dataSource || dataSource.length === 0) {
      this.$element.find('.list').empty()
      return
    }

    // 计算前3名
    const topVoted = [...dataSource]
      .sort((a, b) => (b.voteCount || 0) - (a.voteCount || 0))
      .slice(0, 3)
      .map(item => item.index)

    const topCommented = [...dataSource]
      .sort((a, b) => (b.commentCount || 0) - (a.commentCount || 0))
      .slice(0, 3)
      .map(item => item.index)

    const $list = this.$element.find('.list')
    $list.empty()

    // 应用排序
    const sortedItems = this.config.showSortButton
      ? this.sortItems(dataSource)
      : dataSource

    const filteredItems = this.searchQuery.length > 0
      ? sortedItems.filter((item) => {
          // 如果是快捷标签搜索，只匹配徽章类型
          if (this.isQuickTagSearch) {
            return this.matchBadgeTypeByQuery(item, this.searchQuery.toLowerCase(), topVoted, topCommented)
          }
          // 普通搜索，同时匹配文本和徽章
          return this.matchSearchCriteria(item, this.searchQuery.toLowerCase(), topVoted, topCommented)
        })
      : sortedItems

    filteredItems.forEach((item, index) => {
      const $item = this.createListItem(item, topVoted, topCommented, index)
      $list.append($item)
    })

    // 绑定点击事件
    $list.find('.item').on('click', (e) => {
      const floor = Number.parseInt($(e.currentTarget).data('floor'))
      this.selectItem(floor)
    })
  }

  /**
   * 判断回答项是否匹配搜索条件
   * @param item 回答项
   * @param query 搜索关键词
   * @param topVoted 热评回答索引数组
   * @param topCommented 热议回答索引数组
   */
  private matchSearchCriteria(
    item: IAnswerNavigationItem,
    query: string,
    topVoted: number[],
    topCommented: number[],
  ): boolean {
    // 创建临时 DOM 元素用于文本搜索
    const $item = this.createListItem(item, topVoted, topCommented)

    // 基础搜索条件 - 搜索所有文本内容
    const textContent = $item.text().toLowerCase()
    const basicMatch = textContent.includes(query)

    // 徽章关键词匹配 - 从 searchMap 中获取标签对应的搜索关键词
    const badgeMatch = searchMap.some((tag) => {
      const tagQuery = tag.label.toLowerCase()
      if (query === tagQuery) {
        // 检查是否匹配特定的徽章类型
        return this.matchBadgeType(item, tag.type, topVoted, topCommented)
      }
      return false
    })

    return basicMatch || badgeMatch
  }

  /**
   * 根据搜索查询匹配徽章类型
   */
  private matchBadgeTypeByQuery(
    item: IAnswerNavigationItem,
    query: string,
    topVoted: number[],
    topCommented: number[],
  ): boolean {
    const matchedTag = searchMap.find(tag => tag.label.toLowerCase() === query)
    if (!matchedTag)
      return false

    return this.matchBadgeType(item, matchedTag.type, topVoted, topCommented)
  }

  /**
   * 判断回答项是否匹配特定徽章类型
   * @param item 回答项
   * @param badgeType 徽章类型
   * @param topVoted 热评回答索引数组
   * @param topCommented 热议回答索引数组
   */
  private matchBadgeType(
    item: IAnswerNavigationItem,
    badgeType: string,
    topVoted: number[],
    topCommented: number[],
  ): boolean {
    switch (badgeType) {
      case 'hot':
        return topVoted.includes(item.index) || topCommented.includes(item.index)
      case 'top-vote':
        return topVoted.includes(item.index)
      case 'top-comment':
        return topCommented.includes(item.index)
      case 'liked':
        return /取消喜欢/.test(item.likeText || '')
      case 'upvoted':
        return (item.voteText || '').includes('已赞同')
      default:
        return false
    }
  }

  /**
   * 创建列表项 DOM
   */
  private createListItem(
    item: IAnswerNavigationItem,
    topVoted: number[],
    topCommented: number[],
    index?: number,
  ): JQuery {
    const hasUpvoted = (item.voteText || '').includes('已赞同')
    const hasLiked = /取消喜欢/.test(item.likeText || '')

    const badges: { type: string, text: string }[] = []
    if (topVoted.includes(item.index)) {
      badges.push({ type: 'top-vote', text: `🔥 热评` })
    }
    if (topCommented.includes(item.index)) {
      badges.push({ type: 'top-comment', text: `💬 热议` })
    }

    // 格式化更新时间
    const formatUpdateTime = (time?: string) => {
      if (!time)
        return '未知'

      return ToolKit.time.formatRelativeTime(time)
    }

    return $(`
    <div class="item ${item.highlight ? 'highlighted' : ''}" ${index !== undefined ? `data-index="${index}"` : ''} data-floor="${item.floorCount}">
      <img class="avatar" src="${item.avatar || this.emptyAvatarUrl}" alt="${item.username}">
      <div class="content">
        <div class="header">
          <span class="username">${item.username}</span>
          <span class="floor">${item.floorCount}楼</span>
          ${hasUpvoted ? '<span class="badge upvoted active">已赞同</span>' : ''}
          ${hasLiked ? '<span class="badge liked active">喜欢</span>' : ''}
          ${badges.map(badge => `
            <span class="badge ${badge.type}">${badge.text}</span>
          `).join('')}
        </div>
        <p class="excerpt">${item.excerpt}</p>
        <div class="footer">
          <span class="stat votes">
            <span class="icon">👍</span> 
            <span class="count">${item.voteText}</span>
          </span>
          <span class="stat comments">
            <span class="icon">💬</span> 
            <span class="count">${item.commentText}</span>
          </span>
          <span class="stat time">
            <span class="icon">🕒</span>
            <span class="count">${formatUpdateTime(item.updateTime)}</span>
          </span>
        </div>
      </div>
    </div>
  `)
  }

  private selectItem(floor: number): void {
    this.setCurrentIndex(floor)
    this.renderCurrentItem(floor)
    this.closeDropdown()
    this.emit('navigate', floor)
  }

  setCurrentIndex(index: number): void {
    this.currentIndex = index
    this.updateCounter()
  }

  private updateCounter(): void {
    this.$element?.find('.current-index').text(this.currentIndex)
    this.$element?.find('.total-count').text(`/${this.itemsCount}`)
  }

  private emit(event: 'navigate', payload: number): void {
    this.$element?.trigger(event, payload)
  }

  on(event: 'navigate', callback: (index: number) => void): this {
    this.$element?.on(event, (_, index) => callback(index))
    return this
  }

  /**
   * 获取组件样式
   */
  getStyles(): string {
    return `
      ${this.selector} {
        position: fixed;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        z-index: 1000;
        background: var(--${PROJECT_PREFIX}-theme-toolbar-bg) !important;
        box-shadow: var(--${PROJECT_PREFIX}-theme-toolbar-shadow-bg) !important;
        border-radius: 0;
        width: ${PAGE_CONTENT_WIDTH} !important;
        height: ${AnswerNavigator.DOM_HEIGHT} !important;
        
        &.${BodyClasses.IS_EMPTY} {
          display: none !important;
        }
        
        &.position-bottom {
          top: auto;
          bottom: 20px;
        }
        
        &:not(.position-bottom) {
          top: 0;
        }
        
        /* 徽章样式 */
        .badge {
          margin-left: 8px;
          padding: 2px 6px;
          border-radius: 10px;
          font-size: 11px;
          font-weight: 500;
        
          ${generateBadgeStyles(badgeStyleConfigs)}
        }

        .current-item {
          display: flex;
          align-items: center;
          padding: 12px 16px;
          cursor: pointer;
          user-select: none;
          
          .badge {
            vertical-align: middle;
          }
          
          .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 12px;
            border: 2px solid var(--${PROJECT_PREFIX}-theme-primary) !important;
          }
          
          .meta {
            flex: 1;
            min-width: 0;
            
            .header {
              display: flex;
              align-items: baseline;
              margin-bottom: 4px;
              
              .username {
                font-weight: 600;
                color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                max-width: 150px;
              }
              
              .floor {
                margin-left: 8px;
                font-size: 13px;
                color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
              }
            }
            
            .stats {
              display: flex;
              gap: 12px;
              font-size: 13px;
              
              .stat {
                display: flex;
                align-items: center;
                color: var(--${PROJECT_PREFIX}-theme-secondary) !important;
                
                .icon {
                  margin-right: 4px;
                  font-size: 14px;
                }
              }
            }
          }
          
          .navigator-info {
            padding: 0 8px !important;

            span {
              font-size: 13px;
              color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
            }
          }
          
          .toggle {
            background-image: var(${ThemeVarService.getInstance().generateIcon(ICON_IDS.navigation.arrowsDown)}) !important;
            background-repeat: no-repeat !important;
            background-size: 24px !important;
            width: 24px !important;
            height: 24px !important;
            background-position: center !important;
          }
        }
        
        .dropdown {
          max-height: 0;
          overflow: hidden;
          transition: max-height 0.3s ease;
          border-radius: 0 0 12px 12px;
          background: var(--${PROJECT_PREFIX}-theme-toolbar-bg) !important;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          
          .search-box {
            padding: 12px;
            position: relative;
            display: flex;
            flex-direction: column;
            gap: 8px;
            
            .search-input-container {
              position: relative;

              input {
                box-sizing: border-box !important;
                width: 100%;
                padding: 8px 12px 8px 36px;
                border-radius: 20px;
                border: 1px solid var(--${PROJECT_PREFIX}-theme-border) !important;
                outline: none;
                font-size: 14px;
                
                &:focus {
                  border-color: var(--${PROJECT_PREFIX}-theme-primary) !important;
                }
              }
              
              .search-icon {
                position: absolute;
                left: 12px;
                top: 50%;
                transform: translateY(-50%);
                color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
              }
            }
          }
          
           .sort-box {
              display: flex;
              justify-content: flex-end;
              align-items: center;
              padding: 0 12px 8px;
              
              .sort-button {
                background: none;
                border: none;
                cursor: pointer;
                padding: 4px;
                border-radius: 4px;
                color: var(--${PROJECT_PREFIX}-theme-text-secondary);
                
                &:hover {
                  background: rgba(0, 0, 0, 0.05);
                  color: var(--${PROJECT_PREFIX}-theme-text-primary);
                }
                
                svg {
                  display: block;
                  fill: currentColor;
                }
              }
              
              .sort-content {
                font-size: 12px !important;
                color: var(--${PROJECT_PREFIX}-theme-text-secondary);
              }
            }
          
          .list {
            max-height: 60vh;
            overflow-y: auto;
            padding-bottom: 8px;
            
            .item {
              display: flex;
              padding: 12px 16px;
              cursor: pointer;
              
              &:hover {
                background: var(--${PROJECT_PREFIX}-theme-dropdown-bg-hover) !important;
              }
              
              &.highlighted {
                background: var(--${PROJECT_PREFIX}-highlight-color) !important;
              }
              
              .avatar {
                width: 32px;
                height: 32px;
                border-radius: 50%;
                margin-right: 12px;
                flex-shrink: 0;
              }
              
              .content {
                flex: 1;
                min-width: 0;
                
                .header {
                  display: flex;
                  align-items: baseline;
                  margin-bottom: 4px;
                  
                  .username {
                    font-weight: 500;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    max-width: 120px;
                    color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
                  }
                  
                  .floor {
                    margin-left: 8px;
                    font-size: 12px;
                    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
                  }
                }
                
                .excerpt {
                  margin: 4px 0;
                  font-size: 13px;
                  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                  overflow: hidden;
                }
                
                .footer {
                  display: flex;
                  gap: 12px;
                  font-size: 12px;
                  
                  .stat {
                    display: flex;
                    align-items: center;
                    color: var(--${PROJECT_PREFIX}-theme-secondary) !important;
                    
                    .icon {
                      margin-right: 4px;
                      font-size: 12px;
                    }
                  }
                }
              }
            }
          }
        }
        
        &.expanded {
          .dropdown {
            max-height: ${this.config.maxHeight};
          }
          .toggle {
            transform: rotate(180deg);
          }
        }
      }
      
      @media (max-width: 768px) {
        .clear-icon {
          right: 20px;
          font-size: 14px;
        }
      
        .quick-search-tags {
          gap: 6px;
          
          .tag {
            padding: 3px 6px;
            font-size: 11px;
          }
        }
        ${this.selector} {
          width: 95%;
          
          &.position-bottom {
            bottom: 10px;
          }
          
          &:not(.position-bottom) {
            top: 10px;
          }
          
          .current-item {
            padding: 8px 12px;
          }
        }
      }
    `
  }

  applyConfig(config: Partial<Config>): void {
    super.updateConfig(config)
    this.mount()
    logger.info(`[${this.name}] Config updated and apply`, this.config)
  }
}
